package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.sentiment.bean.LogOperation;
import com.sentiment.database.bean.User;
import com.sentiment.database.bean.UserLog;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String methodName = request.getParameter("method");
		try {
			Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 登陆
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String error = null;

		HttpSession httpsession = request.getSession();
		Subject subject = SecurityUtils.getSubject();
		String clientCheckcode = request.getParameter("checkCode");
		String serverCheckcode = (String) httpsession.getAttribute("CheckCode");
		if (!clientCheckcode.equalsIgnoreCase(serverCheckcode)) {
			error = "验证码错误";
		} else {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			try {
				subject.login(token);
			} catch (UnknownAccountException e) {
				error = "用户名/密码错误";
			} catch (IncorrectCredentialsException e) {
				error = "用户名/密码错误";
				User user = new User();
				user = user.getUserByUserCode(username);
				Session session = subject.getSession();
				UserLog log = new UserLog(user.get_id(), Format.date2String(new Date(), 3),
						LogOperation.illegallogin_passworderror, session.getHost());
				DbUtil db = new DbUtil();
				db.openConnection(UserLog.dbName, UserLog.collection);
				db.insert(log.toDocument());
				db.closeConnection();
			} catch (LockedAccountException e) {
				error = "账号被锁定";
			} catch (AuthenticationException e) {
				// TODO Auto-generated catch block
				error = "其他错误：" + e.toString();
			}
		}
		if (error != null) {// 输入账号或密码错误
			request.setAttribute("errorInfo", error);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		} else {// 登录成功
				// 设置session有效时间
			Session session = subject.getSession();
			// //测试用 8秒失效
			// session.setTimeout(8000);
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			UserLog log = new UserLog(activeUser.getUser_id(), Format.date2String(new Date(), 3), LogOperation.login,
					session.getHost());
			DbUtil db = new DbUtil();
			db.openConnection(UserLog.dbName, UserLog.collection);
			db.insert(log.toDocument());
			db.closeConnection();
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}

	}

	/**
	 * 退出
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		UserLog log = new UserLog(activeUser.getUser_id(), Format.date2String(new Date(), 3), LogOperation.loginout,
				session.getHost());
		DbUtil db = new DbUtil();
		db.openConnection(UserLog.dbName, UserLog.collection);
		db.insert(log.toDocument());
		db.closeConnection();
		response.sendRedirect(request.getContextPath() + "/logout.jsp");

	}
}
